(async function () {
    let bookmark_info;
    let result = await chrome.storage.sync.get(StorageKeys);
    let mappings = JSON.parse(result[StorageKey.BOOKMAP_MAPPINGS] || DefaultBookmarkMappings);
    let previsousFolder = result[StorageKey.PREVIOUS_FOLDER];
    let mutexRules = JSON.parse(result[StorageKey.MUTEXT_RULES] || DefaultMutextRules);
    let mutextSameIndex = result[StorageKey.MUTEX_SAME_INDEX] == 1;
    let tabs = await chrome.tabs.query({
        active: true,
        currentWindow: true
    });
    let tab = tabs[0];
    var tabId = tab.id;
    var tabUrl = tab.url;
    let preferedFolder;
    for (let mapping of mappings) {
        if (new RegExp(mapping[0]).test(tab.url)) {
            preferedFolder = mapping[1];
            break;
        }
    }
    let selectedFolder;
    let bookmarkTreeNodes = await chrome.bookmarks.getTree();
    bookmark_info = findBookmarkByUrl(bookmarkTreeNodes, tab.url);
    let folderIds = recursiveBookmarkTreeNodes(bookmarkTreeNodes);
    let titles = folderIds.map((nodeid, i) => {
        let node;
        let titles = [];
        let tmpid = nodeid;
        while (node = id2node[tmpid]) {
            titles.unshift(node.title);
            tmpid = node.parentId;
        }
        let selected = false;
        if (bookmark_info) {
            selected = bookmark_info.parentId == nodeid;
        } else if (preferedFolder) {
            selected = titles.join(folder_path_separtor) == preferedFolder;
        } else if (previsousFolder) {
            selected = previsousFolder == nodeid;
        } else {
            selected = i == 0;
        }
        $("#folder").append(`<option value="${nodeid}" ${selected ? "selected" : ""}>${titles.join(folder_path_separtor)}</option>`)
        return titles;
    });
    if (!bookmark_info) { // 需要创建新书签
        $('#title').val(tab.title);
        $('#url').val(tab.url);
        let parentId = $("#folder option:selected").val();
        let parentNode = id2node[parentId];
        let matchedMutexRules = mutexRules.filter(v => new RegExp(v).test(tab.url));
        let bookmark_index = null;
        // 检查互斥逻辑
        let mutexBookmarks = [];
        for (let id in id2node) {
            let node = id2node[id];
            if (node?.url) {
                if (matchedMutexRules.some(rule => {
                    const reg = new RegExp(rule);
                    let node_matches = reg.exec(node.url);
                    if (node_matches) {
                        let tab_matches = reg.exec(tab.url);
                        if (tab_matches && tab_matches.length == node_matches.length && tab_matches.every((v, i) => i == 0 || v == node_matches[i])) {
                            return true;
                        }
                    }
                })) { // 互斥书签
                    if (mutextSameIndex) {
                        bookmark_index = node.index;
                    }
                    parentNode.children = parentNode.children.filter(child => {
                        return child.id != node.id;
                    });
                    await chrome.bookmarks.remove(node.id);
                }
            }
        }
        if (bookmark_index == null) {
            bookmark_index = parentNode.children.length;
        } else {
            bookmark_index = Math.min(parentNode.children.length, bookmark_index);
        }
        bookmark_info = await chrome.bookmarks.create({
            parentId: parentId,
            index: bookmark_index,
            title: $("#title").val(),
            url: $("#url").val(),
        });
        if (result[StorageKey.AUTO_CLOSE_POPUP] == 1) {
            window.close();
        }
    } else { // 已有书签
        $('#title').val(bookmark_info.title);
        $('#url').val(bookmark_info.url);
    }


    $("#add").click(async function () {
        if (bookmark_info.parentId != $("#folder option:selected").val()) {
            await chrome.bookmarks.move(bookmark_info.id, {
                parentId: $("#folder option:selected").val(),
            });
        }
        let changes;
        if (bookmark_info.title != $("#title").val()) {
            if (!changes) changes = {};
            changes.title = $("#title").val();
        }
        if (bookmark_info.url != $("#url").val()) {
            if (!changes) changes = {};
            changes.url = $("#url").val();
        }
        if (changes) {
            await chrome.bookmarks.update(bookmark_info.id, changes);
        }
        await chrome.storage.sync.set({
            [StorageKey.PREVIOUS_FOLDER]: $("#folder option:selected").val(),
        });
        window.close();
    });

    $("#del").click(async function () {
        await chrome.bookmarks.remove(bookmark_info.id)
        window.close();
    });
})();